#include "music.h"
#include "ui_music.h"
#include<QListWidgetItem>
music::music(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::music)

{
        ui->setupUi(this);
        musicstate=false;
        p = new SearchSelect(ui->widget_2);//搜索框
        p1= new tabwidget(ui->widget_2);
        p1->hide();
        connect(p->player, &QMediaPlayer::positionChanged, this, &music::positionChanged);
        QString itemName[] = {"搜索","收藏"};

        int row = 0;
        //把字符串数组作为选项加入到列表界面中
        for (QString var : itemName) {
            //  QListWidgetItem *newItem = new QListWidgetItem;//创建一个列表项
            //在row行插入选项，选项的文本是字符串变量var
            ui->listWidget->insertItem(row, var);
            row++;
        }






}


music::~music()
{

}

void music::on_pushButton_clicked()
{
    QString seachText = ui->lineEdit->text();
    //向指定的网址发送一个请求，请求需要一个QNetworkRequest对象，该对象是一个网址
    //请求对象需要用get函数来执行
    p->manager->get(QNetworkRequest(QUrl(QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10").arg(seachText))));
    p->vMusicInfo.clear();//清空数组中上一首歌的内容
}

void music::positionChanged(qint64 position)//position是播放的毫秒，除以总时长就是进度
{
    if(p->playIndex != -1)//判断当前播放的歌曲的下标是否正确
    {
        // int pos = (double(position)/vMusicInfo[playIndex].duration)*100;//当前播放的百分比
        ui->horizontalSlider->setValue(position);
        ui->horizontalSlider->setRange(0,p->vMusicInfo[p->playIndex].duration);
    }
}


void music::on_pushButton_2_clicked()
{
    if(musicstate==false)
    {
        p->player->pause();
        musicstate=true;
    }else
    {
        p->player->play();
        musicstate=false;
    }
}


void music::on_horizontalSlider_sliderMoved(int position)
{
    p->player->setPosition(position);
}


void music::on_pushButton_3_clicked()
{
QString url = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(p->vMusicInfo[p->playIndex].id);
    p->playIndex++;
qDebug()<<p->playIndex;
if(p->playIndex>(p->vMusicInfo.size()-1))
    {
       p->playIndex=0;


    }
    p->player->setSource(QUrl(url));//媒体播放器设置音频来源
    p->player->play();
}


void music::on_pushButton_4_clicked()
{
  QString url = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(p->vMusicInfo[p->playIndex].id);
    p->playIndex--;
   qDebug()<<p->playIndex;
  if(p->playIndex==0)
    {
        p->playIndex= p->vMusicInfo.size()-1;
    }
  p->player->setSource(QUrl(url));//媒体播放器设置音频来源
  p->player->play();
}



void music::on_listWidget_currentRowChanged(int currentRow)
{
    if(currentRow==0)
    {

        p->show();
        p1->hide();
    }
    else if(currentRow==1)
    {
        p->hide();
        p1->show();
    }

}

